# This is a sample Python script.

# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.

import cv2 as cv
import numpy as np
import point
import math


def resize_img(image, height=1800):
    h, w = image.shape[:2]
    pro = height / h
    s_w = int(w * pro)
    s_h = int(height)
    size = (s_w, s_h)
    img = cv.resize(image, size)
    return img, s_h, s_w, pro


def angle(v1, v2):
    dx1 = v1[2] - v1[0]
    dy1 = v1[3] - v1[1]
    dx2 = v2[2] - v2[0]
    dy2 = v2[3] - v2[1]
    angle1 = math.atan2(dy1, dx1)
    angle1 = int(angle1 * 180 / math.pi)
    angle2 = math.atan2(dy2, dx2)
    angle2 = int(angle2 * 180 / math.pi)
    # print(angle2)
    if angle1 * angle2 >= 0:
        included_angle = angle1 - angle2
    else:
        included_angle = abs(angle1) + abs(angle2)
        if included_angle > 180:
            included_angle = 360 - included_angle
    return included_angle


# path = '/Users/wanggh/Desktop/a.jpeg'
# path = '/Users/wanggh/Desktop/original.jpeg'
path = '/Users/wanggh/Desktop/b.jpeg'

default_pro = 0.76
src = cv.imread(path)
src, src_h, src_w, src_pro = resize_img(src)
# 灰度
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
# 高斯平滑
gray = cv.GaussianBlur(gray, (3, 3), sigmaX=5, sigmaY=5, borderType=cv.BORDER_DEFAULT)
# 边缘检测
gray = cv.Canny(gray, 25, 50, apertureSize=3, L2gradient=False)
# 膨胀操作，尽量使边缘闭合
kernel = np.ones((3, 3), np.uint8)
gray = cv.dilate(gray, kernel, iterations=0)
ret, thresh = cv.threshold(gray, 127, 255, cv.THRESH_BINARY)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
max_contour = []
# approx_arr = []
max_x = 0
min_x = 0
max_y = 0
min_y = 0
lt_coordinate = True
rt_coordinate = True
lb_coordinate = True
rb_coordinate = True
point_dict = {}
for contour in contours:
    hull = cv.convexHull(contour)
    epsilon = 0.02 * cv.arcLength(contour, True)
    approx = cv.approxPolyDP(hull, epsilon, True)
    if len(approx) == 4:
        currentArea = cv.contourArea(approx)
        if 2400 < currentArea < 4000:
            x, y, w, h = cv.boundingRect(approx)
            p = point.Point(x, y, w, h)
            if x <= 675:
                if y <= 900 and lt_coordinate:
                    p.x = x - 8
                    p.y = y - 20
                    point_dict['lt'] = p
                    lt_coordinate = False
                elif lb_coordinate:
                    point_dict['lb'] = p
                    lb_coordinate = False
            else:
                if y <= 900 and rt_coordinate:
                    point_dict['rt'] = p
                    rt_coordinate = False
                elif rb_coordinate:
                    point_dict['rb'] = p
                    rb_coordinate = False

# 确定四个角
lt = point_dict['lt']
lb = point_dict['lb']
rt = point_dict['rt']
rb = point_dict['rb']
# 计算夹角
a = angle([lt.x, lt.y, lb.x, lb.y], [lt.x, lt.y, lt.x, lb.y])
height = 1800
width = 1350
matRotate = cv.getRotationMatrix2D((height, width), a, 0.7)  # mat rotate 1 center 2 angle 3 缩放系数
# dst = cv.warpAffine(src, matRotate, (height, width))
# cv.rectangle(dst, (lt.x, lt.y), (lt.x + lt.w, lt.y + lt.h), (0, 0, 0), 2)
# dst = dst[lt.y:lt.y]
cv.rectangle(src, (lt.x, lt.y), (lt.x + lt.w, lt.y + lt.h), (0, 0, 0), 2)
# cv.rectangle(src, (lb.x, lb.y), (lb.x + lb.w, lb.y + lb.h), (0, 255, 0), 2)
cv.imshow("test", src)
cv.waitKey(0)
cv.destroyAllWindows()
